<%@ page pageEncoding="UTF-8"%>
<%@ page language="java" import="java.util.*"  import="java.util.regex.Matcher"
         import="java.util.regex.Pattern,com.alibaba.fastjson.TypeReference" %>
<%@ page import="com.tianxiabuyi.Message" %>
<%@ page import="com.tianxiabuyi.Input" %>
<%@ page import="com.tianxiabuyi.model.pojo.Hospital" %>
<%@ page import="com.tianxiabuyi.persist.QBuilder" %>
<%@ page import="com.tianxiabuyi.model.pojo.Dept" %>
<%@ page import="com.tianxiabuyi.model.pojo.User" %>
<%@ page import="com.tianxiabuyi.persist.DBTools" %>
<%@ page import="static com.tianxiabuyi.utils.ConstantUtil.STATUS_ENABLE" %>
<%@ page import="com.tianxiabuyi.persist.Where" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="com.tianxiabuyi.model.pojo.News" %>
<%@ page import="com.tianxiabuyi.utils.Tools" %>
<%@ page import="com.tianxiabuyi.utils.JSONUtil" %>
<%@ page import="com.tianxiabuyi.utils.ImageUtil" %>
<%@ page import="static com.tianxiabuyi.utils.ConstantUtil.STATUS_DISABLE" %>
<%@ page import="org.jsoup.select.Elements" %>
<%@ page import="org.jsoup.Jsoup" %>
<%!
    public final static String PATTERN = "<img src=\'http://[^>]*?>";

    // 获取图片的像素
    public static String pixel (String imgStr) {
        Pattern pattern =  Pattern.compile("width=\".*?\"");
        Matcher m = pattern.matcher(imgStr);
        String width = "";
        String height = "";
        while(m.find()) {
            width = m.group().split("width=\"")[1].split("\"")[0].trim();
        }
        pattern =  Pattern.compile("height=\".*?\"");
        m = pattern.matcher(imgStr);
        while(m.find()) {
            height = m.group().split("height=\"")[1].split("\"")[0].trim();
        }
        if ("".equals(width)) {
            return "";
        }
        return width + " * " + height;
    }

//    public Map<String, String>  getImg(String content, String pattern) {
//        Map<String, String>  resMap = new HashMap<String, String> ();
//        ArrayList listImg = new ArrayList();
//        Pattern p1 = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
//        Matcher m1 = p1.matcher(content);
//        int j = 0;
//        while (m1.find()) {
//            String imgStr = m1.group();
//            String pixel = pixel(imgStr);
//            Matcher m3  = Pattern.compile("src\\s*=\\s*'?(.*?)('|>|\\s+)").matcher(imgStr);
//            while(m3.find()){
//                imgStr = m3.group(1) + "";
//            }
//            Map map = new HashMap();
//            map.put("ref", "!--IMG#" + j + "--");
//            map.put("src", imgStr);
//            map.put("pixel", pixel);
//            listImg.add(map);
//            ++j;
//        }
//        Pattern p = Pattern.compile("<img[^>]*?>",Pattern.CASE_INSENSITIVE);
//        Matcher m = p.matcher(content);
//        int i = 0;
//        while (m.find()) {
//            content =content.replaceFirst(m.group(), "!--IMG#" + i + "--");
//            i++;
//        }
//        resMap.put("imgs", JSONUtil.toJson(listImg).replaceAll("\"", "\\\""));
//        resMap.put("content", content);
//        return resMap;
//    }

    // 替换抓取新闻标题中可能出现的特殊字符
    private String replaceTitle(String title) {
        title = Tools.getDesc(title, "");
        title = title.replaceAll("\"", "&quot;").replaceAll(":", "&#58;");
        return title;
    }

    // 替换新闻内容中的html标签
    private String replaceContent(String html) {
        html = Tools.getDesc(html, "");
        html = html.toLowerCase();
        html = html.replaceAll("<p[^>]*?>", "<p>");
        html = html.replaceAll("<div[^>]*?>", "<p>");
        html = html.replaceAll("</div>", "</p>");
        html = html.replaceAll("<font[^>]*?>", "");
        html = html.replaceAll("<b(?!r)[^>]*?>", "");
        html = html.replaceAll("<span[^>]*?>","");
        html = html.replaceAll("</span>","");
        html = html.replaceAll("</font>","");
        html = html.replaceAll("<br[^>]*?>","<br/>");
        html = html.replaceAll("<style[^>]*?>[\\s\\S]*?<\\/style>","");
        html = html.replaceAll("<a[^>]*?>","");
        html = html.replaceAll("</a>", "");
        html = replaceTitle(html);
        int i = 0;
        while(html.indexOf("<img") > -1) {
            html = html.replaceFirst("<img[^>]*?>", "!--IMG#" + (i++)  + "--");
        }
        return html;
    }

    // 解析返回本地服务器地址集合
    private String imgs(org.jsoup.nodes.Element content) {
        Elements imgs = content.select("img");
        List<HashMap<String, String>> imgsJson = new ArrayList<HashMap<String, String>>();
        int size = imgs.size();
        for(int i = 0; i < size; i++) {
            String src = imgs.get(i).attr("src").toString();
            String pixel  = "550 * 366";
            String style = imgs.get(i).attr("style").toString();
            // 存入HashMap中
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("ref","!--IMG#" + i + "--");
            map.put("pixel", pixel);
            map.put("src", src);
            map.put("style", style);
            // 循环添加某篇新闻
            imgsJson.add(map);
        }
        return JSONUtil.toJson(imgsJson);
    }

    //获取验证码
    public Message toSms(Input input){
        Message msg = new Message("发送成功");
        String content = input.getDesc("content","");
        Integer hospital = input.getInt("hospital",-1);
        //医院
        List<Hospital> hospitalList =  QBuilder.db("basedb").queryHql("from hospital as hh where hh.name like \'%"+content+"%\'"+" and (hospital = 1070 or parent =1070)");
        //科室
        List<Dept> deptList =  QBuilder.db("basedb").queryHql("from Dept as dd where hospital in (select new map (hospital as h) from hospital as s where hospital = 1070 or parent =1070) and dd.deptName like '%"+ content +"%'");
        //医生
        List<User> userList =  QBuilder.db("basedb").queryHql("from User as u where hospital in (select new map (hospital as h) from hospital as s where hospital = 1070 or parent =1070) and u.name like '%"+ content +"%' and type = 200");

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("hospital",hospitalList);
        map.put("dept",deptList);
        map.put("doctor",userList);


        msg.put("data",map);
        //查询所有不记录
        if(content == null || content.equals("")){
            msg.put("errcode",0);
            msg.put("errmsg","查询完成");

            return msg;
        }

        //查询完成把搜索记录进行存储 （存在的更新搜索时间，不存在的进行增加。）


        List<Map> historyList = QBuilder.db("basedb").queryHql("select new map(id as id) from history_serch where  content = '"+ content+"'");//查询当前用户是否存在这个历史记录

        int num = 1;

        if(historyList == null || historyList.size() ==0){
            Map<String,Object> historyMap = new HashMap<String,Object>();

            // historyMap.put("uid",Integer.parseInt(uid));
            historyMap.put("content",content);
            historyMap.put("hospital",hospital);
            historyMap.put("create_time", System.currentTimeMillis());
            historyMap.put("status", STATUS_ENABLE);

            historyMap.put("json", "{}");

            DBTools.db("basedb").addItem("history_serch", historyMap);
        }else{

            String hql = "update history_serch set create_time ="+System.currentTimeMillis()+" where id = "+historyList.get(0).get("id")+"";
            num = QBuilder.db("basedb").execHQL(hql);
        }
        if(num == 0){
            msg.put("errcode",0);
            msg.put("errmsg","历史记录更新失败");

        }else{
            msg.put("errcode",0);
            msg.put("errmsg","查询完成");
        }
        return msg;
    }

    //新闻列表
    Message newsList(Input input) {

        Map map = new HashMap();
        Integer pageNum = input.getInt("page", 1); // 页码
        Integer itemCount = input.getInt("item_count", 12); // 每一页条目
        Integer category = input.getInt("category", 0); //新闻分类
        Integer status = input.getInt("status", 1); //新闻分类
        String table = "News n";
        String order = "desc"; // 排序
        String labelId = input.getDesc("labelId", "-1").replace(".0", ""); // 通过标签与新闻关联查询   不传默认通过category新闻类别查
        Where where = new Where("n.category=", category);

        if (pageNum <= 0 || itemCount <= 0) {
            return new Message(30041, "参数不合法，请输入正确的页码或限值");
        }
        String selectContent = "distinct new map(n.id as id , n.newsId as news_id, n.url as url, n.title as title, n.summary as summary, n.time as time, n.img as img, n.jsonString as json, n.category as category, n.author as author)" ;

        List newsList = QBuilder.db("basedb").select(selectContent).from("News as n").where(new Where("n.hospital=1070").and("n.category=", category).and("n.status = ", status)).page(itemCount, pageNum).order("n.newsId", order).query().getResultObj();
        List<Long> rankCount = QBuilder.db("basedb").select("count(*)").from(table).where(where.and("n.hospital=", "1070").and("n.status = ", status)).order("n.newsId", order).query().getResultObj();
        if (order.equals("asc")) { // 上拉加载时倒序
            Collections.reverse(newsList);
        }
        Message msg = new Message(0);
        Map resultMap = new HashMap();
        Long size = rankCount.get(0);
        resultMap.put("rank", newsList);
        resultMap.put("current_page", pageNum);
        resultMap.put("page_count",  size%itemCount == 0?(size/itemCount):(size/itemCount + 1));
        resultMap.put("count", size);
        msg.put("data", resultMap);
        return msg;
    }

    //设置已发布
    public Message setNews(Input input) {
        Message msg = new Message();

        String news_id = input.getDesc("news_id","39385").replace(".0","");
        Integer status = input.getInt("status",3);
        String hql = "update News set status = "+ status+" where id ="+news_id;
        int num = QBuilder.db("basedb").execHQL(hql);
        if(num == 0){
            return new Message(30041, "修改失败");
        }else{
            msg.put("errorcode",0);
            msg.put("errormsg","发不成功");
            msg.put("data",num);
        }
        return msg;
    }

    //批量发布
    public Message setNewsList(Input input) {
        Message msg = new Message();

        String news_ids = input.getDesc("news_ids","");
        Integer status = input.getInt("status",1);
        String hql = "update News set status = "+ status+" where  id in("+news_ids+")";
        int num = QBuilder.db("basedb").execHQL(hql);
        if(num == 0){
            return new Message(30041, "修改失败");
        }else{
            msg.put("errorcode",0);
            msg.put("errormsg","发布成功");
            msg.put("data",num);
        }
        return msg;
    }
    //展示新闻详情
    public Message news(Input input) {
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", -1);    // 医院编号
        String news_id = input.getDesc("news_id","39385").replace(".0","");
        Integer status = input.getInt("status",1);
        List newsList = QBuilder.db("basedb").queryHql("from News where hospital="+hospital+" and status="+status+" and id="+news_id);
        if(newsList.size() == 0)
            return new Message(30041, "没有这条新闻");
        else
            msg.put("data", newsList.get(0));
        return msg;
    }

    // 添加新闻
    public Message addNews(Input input) {
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", -1);    // 医院编号
        String deptCode = input.getDesc("deptCode","");
        String labelId = input.getDesc("labelId","").replace(".0","");
        String title = input.getDesc("title","");
        String author = input.getDesc("author","");
        String summary = input.getDesc("summary","");
        String content = input.getDesc("content","");
        //Map<String, String> imgMap = getImg(content,  PATTERN);
        Map jsonMap = new HashMap();
        jsonMap.put("attachs", new ArrayList());
        //获取时间
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(cal.getTime());
        //新建新闻对象
        News news = new News();
        news.setTitle(title);
        news.setAuthor(author);
        news.setSummary(summary);
        news.setTime(time);
        news.setHospital(hospital);
        news.setCategory(Integer.valueOf(labelId));
        news.setBranch("dept-"+deptCode);
        news.setHtml(content);
        news.setImg(imgs(Jsoup.parse(content)));
        news.setContent(replaceContent(content));
        //news.setImg(Tools.getDesc(imgMap.get("imgs")));
        List<Map> imgs = JSONUtil.fromJson(news.getImg(), new TypeReference<List<Map>>(){});
        news.setJson(jsonMap);
        if (imgs.size() != 0 ) {
            String url = ImageUtil.small(Tools.getDesc(imgs.get(0).get("src")));
            news.setJson("news_thumbnail", url);
        }
        try {
            DBTools.db("basedb").addItem(news);
            news.setNewsId(news.getId());
            DBTools.db("basedb").modItem(news,news.getId());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setErrcodeAndErrmsg(30041, "新闻添加失败");
        }
        return msg;
    }

    // 删除新闻
    public Message deleteNews(Input input) {
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", -1);    // 医院编号
        String newsId = input.getDesc("news_id","").replace(".0","");
        QBuilder.db("basedb").execHQL("update News set status= " + STATUS_DISABLE + " where hospital=" + hospital + " and id=" + newsId);
        return msg;
    }

    // 修改新闻
    public Message updateNews(Input input) {
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", -1);    // 医院编号
        String newsId = input.getDesc("news_id","").replace(".0","");
        String title = input.getDesc("title","");
        String author = input.getDesc("author","");
        String content = input.getDesc("content","");
        Integer status = input.getInt("status",1);
      //  Map<String, String> imgMap = getImg(content,  PATTERN);
        Map jsonMap = new HashMap();
        jsonMap.put("attachs", new ArrayList());
        String summary = input.getDesc("summary","");
        List<News> list = QBuilder.db("basedb").queryHql("from News where hospital=" + hospital + " and id=" + newsId + " and status=" + status);
        if(list.size() == 0){
            return new Message(30041, "没有这条新闻");
        } else {
            News news = list.get(0);
            news.setTitle(title);
            news.setAuthor(author);
            news.setSummary(summary);
            news.setHtml(content);
            news.setImg(imgs(Jsoup.parse(content)));
            news.setContent(replaceContent(content));
            List<Map> imgs = JSONUtil.fromJson(news.getImg(), new TypeReference<List<Map>>(){});
            news.setJson(jsonMap);
            if (imgs.size() != 0 ) {
                String url = ImageUtil.small(Tools.getDesc(imgs.get(0).get("src")));
                news.setJson("news_thumbnail", url);
            }
            try {
                DBTools.db("basedb").modItem(news,news.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return msg;
    }

    //重点科室
    public Message keySpecialty(Input input){
        Message msg = new Message("查询完成");
        /*********************东台重点专科接口-2017-8-25************************/
        String isType = input.getDesc("isType","");//1 查询  2 设置/取消
        if(isType == null || isType.equals("") || isType.equals("暂无")){
            msg.put("errcode",30041);
            msg.put("errmsg","查询失败，缺少参数isType");

            return msg;
        }

        if(isType.equals("1")){//查询
            int pageCount = input.getInt("pageCount",10);//查询数量
            int pageNo = input.getInt("pageNo",1);//当前页数
            List<Dept> deptList =  QBuilder.db("basedb").queryHql("from Dept as dd where dd.branch in (select new map (hospital as h) from Hospital as s where s.hospital = 1070 or s.parent =1070) and jsonString like '%\"keyspecialty\":\"1\"%' order by cTime desc",pageCount,pageNo);
            List<Map> coutList =  QBuilder.db("basedb").queryHql("select new map(count(*) as count) from Dept as dd where dd.branch in (select new map (hospital as h) from Hospital as s where s.hospital = 1070 or s.parent =1070) and jsonString like '%\"keyspecialty\":\"1\"%' order by id");
            String totalCount = coutList.size() == 0 ? "0" : coutList.get(0).get("count").toString();
            int count = Integer.parseInt(totalCount);
            int total = (count%pageCount == 0) ? count/pageCount : (count/pageCount)+1;
            msg.put("count",total);
            msg.put("pageNo",pageNo);
            msg.put("errcode",0);
            msg.put("errmsg","查询完成");
            msg.put("data",deptList);

            return msg;
        }else if(isType.equals("2")){
            String state = input.getDesc("state","");//1 设置  2 取消
            String deptId = input.getDesc("deptId","");//部门id
            String deptIcon = input.getDesc("deptIcon","");//部门图标
            List<Dept> deptList =  QBuilder.db("basedb").queryHql("from Dept as dd where id = "+deptId+"");
            if(deptList == null || deptList.size()==0){
                msg.put("errcode",30041);
                msg.put("errmsg","查询失败，部门id传参错误");

                return msg;
            }
            Dept dept = deptList.get(0);
            String hql = "update Dept set ";
            String json = dept.getJsonString();
            if(state.equals("1")){

                if(json == null || json.equals("{}")|| json.equals("")){//json为空时
                    json = "{\"keyspecialty\":\"1\",\"deptIcon\":\"" + deptIcon + "\"}";
                }else{
                    if(json.indexOf("\"keyspecialty\":\"1\"") != -1){//防止重复设置
                        msg.put("errcode",30041);
                        msg.put("errmsg","不能重复添加");
                        msg.put("data","");
                        return msg;
                    }else{
                        json = json.replace("}",",\"keyspecialty\":\"1\",\"deptIcon\":\"" + deptIcon + "\"}");
                    }
                }

            }else{//取消
                json = json.replace("\"keyspecialty\":\"1\",\"deptIcon\":\"" + deptIcon + "\"","");
                json = json.replace(",}","}");
            }
            hql += " jsonString ='"+ json +"' , cTime = "+System.currentTimeMillis()+" where id ="+dept.getId();
            System.out.println(hql);
            int num =  QBuilder.db("basedb").execHQL(hql);


            msg.put("errcode",0);
            msg.put("errmsg","设置成功");
            msg.put("data","");
            return msg;
        }else{
            msg.put("errcode",30041);
            msg.put("errmsg","查询失败，参数isType不正确");
            return msg;
        }

    }

    //医院科室列表
    public Message deptList(Input input){
        Message msg = new Message("查询完成");
        List<Map> hospitalList =  QBuilder.db("basedb").queryHql("select new map(id as id,name as name,hospital as hospital ) from Hospital as hh where ( hh.parent =1070) order by hospital ");
        List<Map> deptList =  QBuilder.db("basedb").queryHql("select new map(id as id,deptName as deptName,branch as branch )  from Dept as dd where type = 1 and (dd.branch in (select new map (hospital as h) from Hospital as s where s.hospital = 1070 or s.parent =1070) ) order by id desc");


        List<Map<String ,Object>> list = new ArrayList<Map<String ,Object>>();
        if(hospitalList != null && hospitalList.size() >= 0){
            for(int i =0 ;i < hospitalList.size() ; i++){
                Map hos = hospitalList.get(i);
                Map<String ,Object>  map = new HashMap<String ,Object>();
                map.put("hospital",hos);

                List<Map<String ,Object>> childList = new ArrayList<Map<String ,Object>>();

                for(int j =0 ;j < deptList.size() ; j++){
                    Map dept = deptList.get(j);

                    if(hos.get("hospital").toString().equals(dept.get("branch").toString())){
                        childList.add(dept);
                    }
                }
                map.put("dept",childList);

                list.add(map);
            }
        }
        msg.put("errcode",0);
        msg.put("errmsg","查询完成");
        msg.put("data",list);

        return msg;
    }

    /**
     * @Describe 常见疾病的操作方法
     * @param input
     * @return
     */

    //常见疾病增删改查
    //常见疾病增删改查
    public Message commonDiseases(Input input){
        Message msg = new Message("查询完成");
        int hospital = input.getInt("hospital",-1);
        String type = input.getDesc("type","");//add  delete  update  query

        if(type.equals("add")){//添加常见疾病
            //名称
            String name = input.getDesc("name","");
            //简介内容
            String content = input.getDesc("content","");
            //分组名称
            String tgname = input.getDesc("tgname","");
            //专家ID
            String expertIds = input.getDesc("expertIds","");
            //图片url
            String url  = input.getDesc("url","");

            Map<String,Object> diseasesMap = new HashMap<String,Object>();


            Map<String,Object> typeGroupMap = new HashMap<String,Object>();
            //检查疾病名称是否重复
            List<Map> comList =  QBuilder.db("basedb").queryHql("select new map(id as id) from common_diseases where name ='"+name+"' and status =1");
            if(comList != null && comList.size()>0){
                msg.put("errcode" , 30041);
                msg.put("errmsg" , "疾病名称重复");
                return  msg;
            }
            //查询类别是否存在
            List<Map> groupList =  QBuilder.db("basedb").queryHql("select new map(id as id) from type_group where name ='"+tgname+"' and status =1");
            Serializable  key = null;

            if(groupList == null || groupList.size() == 0){
                typeGroupMap.put("name",tgname);
                typeGroupMap.put("category",1);

                typeGroupMap.put("content",content);
                typeGroupMap.put("hospital",hospital);
                typeGroupMap.put("create_time", System.currentTimeMillis());
                typeGroupMap.put("status", STATUS_ENABLE);

                typeGroupMap.put("json", "{}");
                key = DBTools.db("basedb").addItem("type_group", typeGroupMap);
            }else{
                key = (Serializable)groupList.get(0).get("id");
            }

            diseasesMap.put("name",name);
            diseasesMap.put("content",content);
            diseasesMap.put("tgid",key);
            diseasesMap.put("tgname",tgname);
            diseasesMap.put("expert_ids",expertIds);
            diseasesMap.put("img",url);

            diseasesMap.put("content",content);
            diseasesMap.put("hospital",hospital);
            diseasesMap.put("create_time", System.currentTimeMillis());
            diseasesMap.put("status", STATUS_ENABLE);

            diseasesMap.put("json", "{}");
            Serializable num = DBTools.db("basedb").addItem("common_diseases", diseasesMap);
            msg.put("errcode" , "0");
            msg.put("errmsg" , "添加完成");
            msg.put("data" , num);
        }else if(type.equals("update")){//
            int id = input.getInt("id",-1);
            //名称
            String name = input.getDesc("name","");
            //简介内容
            String content = input.getDesc("content","");
            //分组名称
            String tgname = input.getDesc("tgname","");
            //专家ID
            String expertIds = input.getDesc("expertIds","");
            //图片url
            String url  = input.getDesc("url","");

            Map<String,Object> diseasesMap = new HashMap<String,Object>();


            Map<String,Object> typeGroupMap = new HashMap<String,Object>();
            //检查疾病名称是否重复
            List<Map> comList =  QBuilder.db("basedb").queryHql("select new map(id as id) from common_diseases where  status =1 and name ='"+name+"'  and id !="+id);
            if(comList != null && comList.size()>0){
                msg.put("errcode" , 30041);
                msg.put("errmsg" , "疾病名称重复");
                return  msg;
            }
            //查询类别是否存在
            List<Map> groupList =  QBuilder.db("basedb").queryHql("select new map(id as id) from type_group where name ='"+tgname+"' and status =1");
            Serializable  key = null;

            if(groupList == null || groupList.size() == 0){
                typeGroupMap.put("name",tgname);
                typeGroupMap.put("category",1);

                typeGroupMap.put("content",content);
                typeGroupMap.put("hospital",hospital);
                typeGroupMap.put("create_time", System.currentTimeMillis());
                typeGroupMap.put("status", STATUS_ENABLE);

                typeGroupMap.put("json", "{}");
                key = DBTools.db("basedb").addItem("type_group", typeGroupMap);
            }else{
                key = (Serializable)groupList.get(0).get("id");
            }


            String sql = "";




            String hql = "update common_diseases set name = '"+name +"' ,content = '"+content+"',tgid = "+key+" ,tgname = '"+tgname+"', expert_ids='"+expertIds
                    +"' , img = '"+url+"' , hospital = "+hospital+" where id ="+id;


            int num =  QBuilder.db("basedb").execHQL(hql);
            msg.put("errcode" , "0");
            msg.put("errmsg" , "修改完成");
            msg.put("data" , num);
        }else if(type.equals("delete")){//
            //名称
            int id = input.getInt("id",-1);
            int num =  QBuilder.db("basedb").execHQL("update common_diseases set status = 0 where id ="+id+"");

            msg.put("errcode" , "0");
            msg.put("errmsg" , "删除完成");
            msg.put("data" , num);
        }else if(type.equals("query")){//
            int pageCount = input.getInt("pageCount",10);//查询数量
            int pageNo = input.getInt("pageNo",1);//当前页数
            List<Map> commonList =  QBuilder.db("basedb").queryHql("select new map(id as id,name as name,tgid as tgid,tgname as tgname ,content as content,expert_ids as expert_ids,img as img) from common_diseases where hospital ="+hospital+" and status =1 order by id desc",pageCount,pageNo);
            List<Map> coutList =  QBuilder.db("basedb").queryHql("select new map(count(*) as count) from  common_diseases where hospital ="+hospital+" and status =1");

            String totalCount = coutList.size() == 0 ? "0" : coutList.get(0).get("count").toString();
            int count = Integer.parseInt(totalCount);
            int total = (count%pageCount == 0) ? count/pageCount : (count/pageCount)+1;
            msg.put("pageNo",pageNo);
            msg.put("count",total);
            msg.put("errcode" , "0");
            msg.put("errmsg" , "查询完成");
            msg.put("data" , commonList);
        }else if(type.equals("get")){//获取参数
            int id = input.getInt("id",-1);
            List<Map> commonList =  QBuilder.db("basedb").queryHql("select new map(id as id,name as name,tgid as tgid,tgname as tgname ,content as content,expert_ids as expert_ids,img as img) from common_diseases where id = "+id+" and hospital ="+hospital+" and status =1");//
            if(commonList == null || commonList.size() == 0){
                msg.put("errcode" , 30041);
                msg.put("errmsg" , "该id 没有对应的数据");
                msg.put("data" , "");
            }else{
                Map<String,Object> map = new HashMap<String,Object>();
                if(commonList.get(0).get("expert_ids") != null){
                    String expertIds =  commonList.get(0).get("expert_ids").toString();

                    List<Expert> expertList =   QBuilder.db("basedb").queryHql("from Expert where id in("+ expertIds +")");

                    //专家放入集合
                    map.put("expert",expertList);
                }

                //常见疾病放入集合
                map.put("common_diseases",commonList);


                msg.put("errcode" , "0");
                msg.put("errmsg" , "查询完成");
                msg.put("data" , map);
            }
        } else{// 参数错误
            msg.put("errcode",30041);
            msg.put("errmsg","查询失败，type参数错误");
            msg.put("data","");


        }
        return msg;
    }

    /**
     * 获取分组名称
     * @param input
     * @return
     */
    //常见疾病分组信息
    public Message getGroupType(Input input){
        Message msg = new Message("查询完成");
        String hospital = input.getDesc("hospital","");
        String category = input.getDesc("category","");

        List<Map> groupList =  QBuilder.db("basedb").queryHql("select new map(name as name ,id as id)  from type_group where hospital="+hospital+" and category ="+category);

        msg.put("errcode" , "0");
        msg.put("errmsg" , "添加完成");
        msg.put("data" , groupList);
        return msg;
    }

    //获取  医院  科室   医生   三级联动数据
    public Message queryExpertList(Input input){
        Message msg = new Message("查询完成");
        String hospital = input.getDesc("hospital","");
        //东台查询 医院 科室  专家的集合
        List<Map> hospitalList =  QBuilder.db("basedb").queryHql("select new map(id as id,name as name,hospital as hospital ) from Hospital as hh where status =1 and ( hh.parent =1070) order by hospital ");
        List<Map> deptList =  QBuilder.db("basedb").queryHql("select new map(id as id,deptName as deptName,branch as branch )  from Dept as dd where status =1  and type =2 and dd.branch in (select new map (hospital as h) from Hospital as s where s.hospital = 1070 or s.parent =1070 )   order by id desc");

        List<Map> expertList =  QBuilder.db("basedb").queryHql("select new map(id as id,name as name,hospital as hospital ,deptId as deptId) from Expert as dd where status =1 and dd.hospital in (select new map (hospital as h) from Hospital as s where s.hospital = 1070 or parent =1070) order by id desc ");


        List<Map<String ,Object>> list = new ArrayList<Map<String ,Object>>();
        if(hospitalList != null && hospitalList.size() >= 0){
            for(int i =0 ;i < hospitalList.size() ; i++){
                Map hos = hospitalList.get(i);
                Map<String ,Object>  map = new HashMap<String ,Object>();
                map.put("hospital",hos);

                List<Map<String ,Object>> childList = new ArrayList<Map<String ,Object>>();

                for(int j =0 ;j < deptList.size() ; j++){
                    Map dept = deptList.get(j);
                    Map<String ,Object>  deptMap = new HashMap<String ,Object>();
                    List<Map<String ,Object>> childExpertList = new ArrayList<Map<String ,Object>>();
                    for(int k =0 ; k < expertList.size() ; k++){
                        Map expert = expertList.get(k);

                        if(expert.get("deptId").toString().equals(dept.get("id").toString())){
                            childExpertList.add(expert);
                        }
                    }
                    deptMap.put("dept",dept);
                    deptMap.put("expert",childExpertList);
                    if(hos.get("hospital").toString().equals(dept.get("branch").toString())){
                        childList.add(deptMap);
                    }
                }
                map.put("dept",childList);

                list.add(map);
            }
        }
        msg.put("errcode",0);
        msg.put("errmsg","查询完成");
        msg.put("data",list);
        return msg;
    }
%>